let http = {}
import { ElMessageBox } from 'element-plus'
import axios from 'axios'
import store from '@/stores';
import config from '@/config';
import { getToken } from "@/utils/token";
import router from '@/router'
import modal from '@/utils/modal'

let isRelogin = { show: false }

// 自定义异常处理方式
function custErrFun(err) {
    console.log('err',err)
    if(err.status == 500 || (err.response && err.response.status == 500)){
        modal.msgError(err.response.data.message || '请求失败，请检查网络或联系管理员');
    } else if (err.response && err.response.status !== 200) {
        if(err.response.status == 403){
            modal.msgError(err.response.data.message || '登录状态过期，请重新登录');
            window.location.href = '/'
        } else {
            modal.msgError(err.response.data.message || '请求失败，请检查网络或联系管理员');
        }
    } else if (err.message && err.stack) {
        console.log(err);
    } else {
        modal.msgError('请求失败，请检查网络或联系管理员');
    }
}

// 自定义返回处理
function custResponseFun(res, resolve) {
    // 返回的状态
    const responseStatus = res.data.code
    switch (responseStatus) {
        case 200:
            resolve(res)
            break;
        case 401:
            // resolve(res)
            if (!isRelogin.show) {
                isRelogin.show = true
                ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // console.log(store.userStore.token)
                    isRelogin.show = false
                    store.userStore.logout().then(() => {
                        router.push({path: '/login'})
                    })
                }).catch(() => {
                    isRelogin.show = false;
                })
            }
            break;
        case 500:
            resolve(res)
            modal.msgError(res.data.msg||'500')
            break;
    }
}

// get 请求
http.get = function (url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
                params: params || {},
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'Authorization': getToken()
                },
                timeout: config.httpTimeOut
            })
            .then(res => {
                custResponseFun(res, resolve);
            })
            .catch(err => {
                resolve(err)
                custErrFun(err)
            })
    });
};

// POST 请求
http.post = function (url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params, {
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'Authorization': getToken()
                },
                timeout: config.httpTimeOut
            })
            .then(res => {
                custResponseFun(res, resolve);
            })
            .catch(err => {
                resolve(err)
                custErrFun(err)
            })
    });
};
http.download = function (url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params, {
            headers: {
                'Content-Type': 'application/json;charset=UTF-8',
                'Authorization': getToken()
            },
            responseType: 'blob' , //必写
            timeout: config.httpTimeOut
        }).then(res => {
            resolve(res);
        })
            .catch(err => {
                reject(err.data)
            })
    });
}
export default http;
